package com.kaka.bus.engine.repay;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.Toolbar;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kaka.bus.R;
import com.kaka.bus.base.BaseActivity;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.constant.UserConstant;
import com.kaka.bus.engine.repay.detail.RepayDetailActivity;
import com.kaka.bus.util.U;
import com.kaka.bus.view.MutipleLayout;

import java.util.Date;

import butterknife.BindView;

/**
 * Created by OnionMac on 2018/1/18.
 */

public class RepayActivity extends BaseActivity<RepayPresenter> implements RepayContract.View {

    private static final int PAY_CODE = 101;

    public static final String TYPE = "type";
    public static final int TYPE_TERM_NOW = 2;
    public static final int TYPE_ALL = 1;
    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_name)
    TextView mToolbarName;
    @BindView(R.id.toolbar_rl)
    RelativeLayout mToolbarRl;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.pact_progressbar)
    ProgressBar mPactProgressbar;
    @BindView(R.id.pact_webview)
    WebView mPactWebview;
    @BindView(R.id.pact_muti)
    MutipleLayout mPactMuti;


    private int mCurrentType = TYPE_TERM_NOW;
    private String mBrrow_id;

    @Override
    protected void initView() {
        super.initView();
        mToolbarBack.setOnClickListener(v -> finish());
        mToolbarName.setText("付款");
        mPactMuti.setStatus(MutipleLayout.Success);
        U.initWebView(mPactWebview,mPactProgressbar);
        mPactWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mPactWebview.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView wv, String url) {
                if(url == null) return false;
                try {
                    if(url.startsWith("weixin://") || url.startsWith("alipays://") ||
                            url.startsWith("mailto://") || url.startsWith("tel://")) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }
                } catch (ActivityNotFoundException e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    if(url.startsWith("alipays://")){
                        U.getSingleDialog(RepayActivity.this,"提示",
                                "您并未安装支付宝,请使用其他付款方式或者安装支付宝","知道了",null)
                                .show();
                    }else if(url.startsWith("weixin://")){
                        U.getSingleDialog(RepayActivity.this,"提示",
                                "您并未安装微信,请使用其他付款方式或者安装微信","知道了",null)
                                .show();
                    }
                    return true;
                }
                //处理http和https开头的url
                wv.loadUrl(url);
                return true;
            }
        });

        /**
         * js
         */
        mPactWebview.addJavascriptInterface(new JSInterface(),"yhs");
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }

        mBrrow_id = intent.getStringExtra(UserConstant.BORR_ID);
        mCurrentType = intent.getIntExtra(TYPE,TYPE_TERM_NOW);

        String params = Constant.USERID+"="+getUserId()+"&borr_id="+mBrrow_id+"&token="+getToken()+"&type="+mCurrentType+"&_t"+new Date().getTime();
        mPactWebview.loadUrl(Constant.BASE_URL+"user/getRepaymentDetails.action?"+params);
    }

    class JSInterface {

        @JavascriptInterface
        public void openDetails(){
            finish();
        }

        @JavascriptInterface
        public void unionpay(String alsoAmount,String actAmount,String bankId,String borrId){
            runOnUiThread(() -> {
                Intent intent = new Intent(RepayActivity.this, RepayDetailActivity.class);
                intent.putExtra(RepayDetailActivity.REPAY_MONEY,alsoAmount);
                intent.putExtra(RepayDetailActivity.ACT_REPAY_MONEY,actAmount);
                intent.putExtra(RepayDetailActivity.BORROW_ID,borrId);
                intent.putExtra(RepayDetailActivity.BANK_ID,bankId);
                intent.putExtra(TYPE,mCurrentType);
                startActivityForResult(intent,PAY_CODE);
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 确定是还款发出的请求
         */

        if(requestCode == PAY_CODE){
            /**
             * 成功
             */
            if(resultCode == Constant.PAY_SUCCESS){
                finish();
            }else if(resultCode == Constant.PAY_FAILD){
                U.getSingleDialog(this,"提示","抱歉,付款失败","确定",null).show();
            }else{
                U.getSingleDialog(this,"提示","您取消了付款操作","确定",null).show();
            }
            initData();
        }

    }

    @Override
    public void getRepaymentSuccess(String wrapper) {
        mPactWebview.loadDataWithBaseURL(null,wrapper, "text/html",  "utf-8", null);
    }

    @Override
    public void getParamsSuccess(HttpWrapper<String> wrapper) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_h5;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }


}
